import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:video_player/video_player.dart';

class LoadNativeMediaVideo extends StatefulWidget {
  const LoadNativeMediaVideo({super.key});

  @override
  _LoadNativeMediaVideoState createState() => _LoadNativeMediaVideoState();
}

class _LoadNativeMediaVideoState extends State<LoadNativeMediaVideo> {
  VideoPlayerController? _controller;
  XFile? _video;

  // 请求权限的方法
  Future<void> _requestPermission() async {
    final status = await Permission.photos.request();
    if (status.isGranted) {
      _pickVideo();  // 权限被允许后，继续选择视频
    } else {
      // 权限被拒绝
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('权限被拒绝，无法访问相册')),
      );
    }
  }

  // 选择视频的方法
  Future<void> _pickVideo() async {
    final ImagePicker picker = ImagePicker();
    final XFile? pickedFile = await picker.pickVideo(source: ImageSource.gallery);

    if (pickedFile != null) {
      setState(() {
        _video = pickedFile;
      });

      // 创建视频播放器
      _controller = VideoPlayerController.file(File(_video!.path))
        ..initialize().then((_) {
          setState(() {});
          _controller!.play();  // 视频初始化完成后播放
        });
    }
  }

  @override
  void dispose() {
    super.dispose();
    _controller?.dispose();  // 释放播放器资源
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Load Photo Album Video')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            _video == null
                ? const Text('请选择一个视频')
                : _controller!.value.isInitialized
                ? Expanded(child: AspectRatio(
                aspectRatio: _controller!.value.aspectRatio,
                child: VideoPlayer(_controller!)),
            )
                : const CircularProgressIndicator(),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: _requestPermission,
              child: const Text('从相册选择视频'),
            ),
          ],
        ),
      ),
    );
  }
}